package com.dao;

import com.bean.Student;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.utils.PageTools;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class Dao {
    private QueryRunner qr=new QueryRunner(new ComboPooledDataSource());
    public int AllStudentCount() {
        String sql="select count(*) from student";
        try {
            long l = (long) qr.query(sql, new ScalarHandler());
            return (int)l;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return 0;
    }

    public List dimQuery(PageTools pt) {
        String sql="select * from student limit ?,?";
        try {
           return qr.query(sql,new BeanListHandler<>(Student.class),pt.getIndex(),pt.getPagesize());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    /**
     * 查询满足条件的总条数
     * @param input
     * @return
     */
    public int dim2Query(String input) {
        String sql="select count(*) from student where 1=1";
        if (!"".equals(input) && input!=null){
//            sql +=" and ( sname like '%" + input + "%' or sex like '%"+ input + "%')";
            sql +=" and ( sname like '%" + input + "%' or sex like '%"+ input + "%' or hobby like '%" + input + "%')";

        }

        try {
            long l = (long) qr.query(sql, new ScalarHandler());
            return (int)l;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return 0;
    }


    /**
     * 满足条件的分页查询
     * @param input
     * @param pt
     * @return
     */
    public List search(String input, PageTools pt) {
        String sql="select * from student where  1=1";
        if (!"".equals(input) && input!=null){
//            sql+=" and sname like '%" + input + "%'";
            sql +=" and ( sname like '%" + input + "%' or sex like '%"+ input + "%' or hobby like '%" + input + "%')";

        }
        sql+=" limit ?,?";
        try {
            return qr.query(sql,new BeanListHandler<>(Student.class),pt.getIndex(),pt.getPagesize());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    public int delete(String sid) {
        String sql="delete from student where sid=?";
        try {
            return qr.update(sql,sid);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return 0;
    }
}
